﻿using DapperExtensions;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Micro.Extensions.Data
{
    public class CrudRepository<T> : ICrudRepository<T> where T : class
    {
        private readonly IDbContext _dbContext;

        public CrudRepository(IDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 简单获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <param name="readMaster"></param>
        /// <returns></returns>
        public T Get(object id, bool readMaster = false)
        {
            return _dbContext.Get<T>(id, readMaster: readMaster);
        }


        /// <summary>
        /// 插入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void Insert(T entity)
        {

            _dbContext.AddCommand((c, t) =>
            {
                c.Insert(entity, t);
                return Task.FromResult(1);
            });
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities"></param>
        public void Insert(IEnumerable<T> entities)
        {

            _dbContext.AddCommand(
                (c, t) =>
                {
                    c.Insert(entities, t);
                    return Task.FromResult(entities.Count());
                }
            );
        }
        /// <summary>
        /// 简单修改
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void Update(T entity)
        {

            _dbContext.AddCommand((c, t) =>
            {
                var result = c.Update(entity, t);
                return Task.FromResult(result ? 1 : 0);
            });
        }

        /// <summary>
        /// 简单删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void Delete(T entity)
        {

            _dbContext.AddCommand((c, t) =>
            {
                var result = c.Delete(entity, t);
                return Task.FromResult(result ? 1 : 0);
            });
        }
    }
}
